/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-04-27 14:49:28
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2025-05-21 17:45:50
 * @FilePath: \greenbeeadmin\middleware\AdminCheckLogin.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package middleware

import (
	adminService "greenbeeadmin/controllers/admin/service"
	greenbee "greenbeeadmin/controllers/greenbee"
	greenbeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"greenbeeadmin/models"
	"net/http"
	"strings"

	beego "github.com/beego/beego/v2/adapter"
	"github.com/beego/beego/v2/adapter/context"
)

/**
 * @description: admin 过滤中间件
 * @param {[]string} letGoUrlItem 全局放行路由
 * @param {[]string} passItem 权限放行路由
 * @return {*}
 */
func AdminCheckLogin(letGoUrlItem, passItem []string) {

	//admin登录认证中间件过滤器
	var login = func(ctx *context.Context) {
		//fmt.Println("登录验证中间件")
		requestPath := ctx.Request.URL.Path
		requestPath = strings.Replace(requestPath, ".html", "", -1)
		// 放行设置
		//letGoUrlItem := []string{}

		if !greenbeeUtils.InArrayStr(requestPath, letGoUrlItem) && !strings.Contains(ctx.Request.URL.Path, "resource") {
			// 登陆判断
			if !greenbee.IsLogin(ctx) {
				// 跳转登录页,方式：301(永久移动),308(永久重定向),307(临时重定向)
				ctx.Redirect(http.StatusFound, "/admin/login")
				return
			}
			// 权限判断 ...
			//超级管理员判断
			user := ctx.Input.Session("user")
			isAdmin := false
			admin_id := 0
			if user != nil {
				adminuser := user.(models.AdminUser)
				//超级管理员
				if adminuser.Is_admin == 1 {
					isAdmin = true
				}
				admin_id = adminuser.Id
			}
			// 权限验证 （不在放行路由，并且不是超级管理员）
			if !greenbeeUtils.InArrayStr(requestPath, passItem) && !isAdmin {
				// 权限
				userUrls := ctx.Input.Session("userAuthorizationUrls")
				//权限列表失效，重新查询权限列表
				if userUrls == nil && admin_id > 0 {
					var adminUserService adminService.AdminUserService
					authorizationUrls := adminUserService.GetUserAuthorizationUrls(admin_id)
					ctx.Input.CruSession.Set(ctx.Request.Context(), "userAuthorizationUrls", authorizationUrls)
					userUrls = authorizationUrls
				}
				if userUrls != nil {
					authorizationUserUrls := userUrls.([]string)
					//权限不存在
					if !greenbeeUtils.InArrayStr(requestPath, authorizationUserUrls) {
						if ctx.Input.IsGet() {
							ctx.Output.Context.WriteString("<center style='padding:40px;'>暂无权限哦~</center>")
						} else {

							// json返回格式 结构体
							type ReturnMsg struct {
								Code  int         `json:"code"`
								Msg   string      `json:"msg"`
								Count int         `json:"count"`
								Data  interface{} `json:"data"`
							}
							res := ReturnMsg{
								500, "暂无权限，请联系超级管理员", 1, "",
							}
							_ = ctx.Output.JSON(res, true, true)
						}

					}

				}

			}

		}
	}

	// 登录过滤器
	beego.InsertFilter("/admin/*", beego.BeforeRouter, login)
}
